package com.audaque.springboot.foshanupload.web.esdatademo.repository;


import com.audaque.springboot.foshanupload.web.esdatademo.model.pojo.Blog;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.annotations.Highlight;
import org.springframework.data.elasticsearch.annotations.HighlightField;
import org.springframework.data.elasticsearch.annotations.HighlightParameters;
import org.springframework.data.elasticsearch.annotations.Query;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchPage;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 自定义DSL和命名查询都不能动态查询。
 */
@Repository
public interface BlogRepository extends ElasticsearchRepository<Blog, Long> {
    @Highlight(fields = {@HighlightField(name = "title")
    })
    List<SearchHit<Blog>> findByTitle(String title);

    List<Blog> findByTitleAndContent(String title, String content);

    Page<Blog> findByTitleAndContent(String title, String content, Pageable pageable);
    // 这样写不行，查不到数据。原因待确定
    // @Query("{\"bool\":{\"must\":[{\"match\":{\"title\":\":titleParam\"}}," +
    //         "{\"match\":{\"content\":\":contentParam\"}}]}}")
    // List<Blog> findByTitleAndContentCustom(@Param("titleParam") String title, @Param("contentParam") String content);

    @Query("{\"bool\":{\"must\":[{\"match\":{\"title\":\"?0\"}}," +
            "{\"match\":{\"content\":\"?1\"}}]}}")
    List<Blog> listByTitleAndContentDsl(@Param("title") String title, @Param("content") String content);

    @Query("{\"bool\":{\"must\":[{\"match\":{\"title\":\"?0\"}}," +
            "{\"match\":{\"content\":\"?1\"}}]}}")
    Page<Blog> pageByTitleAndContentDsl(@Param("title") String title, @Param("content") String content, Pageable pageable);

    /**
     * 通过描述内容来搜索博客
     *
     * @param descriptiveContent 描述语句
     * @param pageable           分页
     * @return 博客列表
     */
    @SuppressWarnings("SpringDataRepositoryMethodReturnTypeInspection")
    @Highlight(fields = {
            @HighlightField(name = "title", parameters = @HighlightParameters(requireFieldMatch = false)),
            @HighlightField(name = "description", parameters = @HighlightParameters(requireFieldMatch = false)),
    })
    SearchPage<Blog> findByDescriptiveContent(String descriptiveContent, Pageable pageable);


}
